package com.blank.shop.ribbon.consumer;

import com.blank.shop.ribbon.ShopRibbonApplication;
import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.context.annotation.Profile;

/**
 * 此配置类不能被springboot扫描到 ( 定制化的，非全局)
 * <br/>Date 2021/8/26
 * <br/>Time 10:13:50
 *
 * @author _blank
 */
@Configuration
@Profile({ShopRibbonApplication.SERVER_CONSUMER})
public class MyRibbonClientRule {

    @Bean
    @Primary
    public IRule myRandomRule() {
        return new RandomRule();
    }

    @Bean
    public IRule myCustomRoundRobinRule() {
        return new MyCustomRoundRobinRule();
    }

    /**
     * 自己写一个负载均衡轮询
     *
     * @see RoundRobinRule
     */
    static class MyCustomRoundRobinRule extends AbstractLoadBalancerRule {
        @Override
        public void initWithNiwsConfig(IClientConfig iClientConfig) {
        }

        @Override
        public Server choose(Object key) {
            // fixme 没有实现

            final ILoadBalancer loadBalancer = super.getLoadBalancer();
            return loadBalancer.getAllServers().get(0);
        }
    }

}